<template>
	<view class="page_wrapper page_bg">
		<!-- <scroll-view class="main_block" scroll-y="true" scroll-into-view="main_bottom" :scroll-top="scrollTop" >
			<text id="sparkResultBottom" style="width: 100%;flex-wrap:wrap">{{sparkResult}}</text>
		</scroll-view>
		<view class="user_content_block">
			<textarea class="user_content" v-model="TEXT" placeholder="这里你可以随便写你想问的问题"></textarea>
		</view>
		<view class="bottom_btns_block">
			<view class="fcz_btn send_msg" @click="sendMsg()"  v-if="currentStatus !== 'running'">
				发送给萌芽助手
			</view>
			<view class="fcz_btn sending_msg" v-else>
				运行中...
			</view>
		</view> -->
	</view>
</template>

<script>
	import {request} from '@/utils/request.js'
	import {storageData} from '@/utils/storageData.js'
	// import * as base64 from "base-64"
	import CryptoJS from 'crypto-js'
	import parser from 'fast-xml-parser'
	// import * as utf8 from "utf8"
	// import URL from 'url'
	export default {
		// https://spark-api.xf-yun.com/v1.1/chat  V1.5 domain general
		// https://spark-api.xf-yun.com/v2.1/chat  V2.0 domain generalv2
		data() {
			return {
				TEXT: '',
				// 地址必须填写，代表着大模型的版本号！！！！！！！！！！！！！！！！
				httpUrl: "https://spark-api.xf-yun.com/v3.5/chat",
				modelDomain: '', // V1.1-V3.5动态获取，高于以上版本手动指定
				APPID: '95071db1', // 控制台获取填写
				APISecret: 'ZDRjYzA4YWZiOTMwYzRlN2ZjYjIxZjk3',
				APIKey: 'bd4cbe3e2b51d619441ca0632762bf35',
				sparkResult: '对话记录:\r\n',
				historyTextList: [], // 历史会话信息，由于最大token12000,可以结合实际使用，进行移出
				tempRes: '', // 临时答复保存
				scrollTop: 0,
				currentStatus: 'end'
			}
		},
		onLoad() {
			
		},
		methods: {
			
			sendMsg() {
				this.TEXT = this.TEXT.trim()
				if(this.TEXT.length < 5) {
					uni.showModal({
						title: '提示',
						content: '您输入的内容太短，请描述下问题',
						showCancel: false
					})
					return false
				}
				if(this.currentStatus === 'running'){
					return false
				}
				this.currentStatus = 'running'
				const idNo = new Date().getTime() + ''
				const data =  {
					idNo: idNo,
					chatContent: this.TEXT
				}
				// request.postJson(
				// 	'/userChatLogs/idNo,' + idNo, data
				// ).then(res => {
				// 	this.sendToSpark(idNo)
				// }).catch(err => {
				// 	this.currentStatus = 'end'
				// 	console.log(err)
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: err.data.message,
				// 		showCancel: false
				// 	})
				// })
			},
			
			async sendToSpark(idNo) {
				let myUrl = await this.getWebSocketUrl();
				this.tempRes = "";
				// this.sparkResult = "";
				let realThis = this;
				this.socketTask = uni.connectSocket({
					//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
					url: myUrl,
					method: 'GET',
					success: res => {
						console.log(res, "ws成功连接...", myUrl)
						realThis.wsLiveFlag = true;
					}
				})
				realThis.socketTask.onError((res) => {
					console.log("连接发生错误，请检查appid是否填写", res)
				})
				realThis.socketTask.onOpen((res) => {
					this.historyTextList.push({
						"role": "user",
						"content": this.TEXT
					})
					console.info("wss的onOpen成功执行...", res)
					// 第一帧..........................................
					console.log('open成功...')
					let params = {
						"header": {
							"app_id": this.APPID,
							"uid": "aef9f963-7"
						},
						"parameter": {
							"chat": {
								"domain": this.modelDomain,
								"temperature": 0.5,
								"max_tokens": 1024
							}
						},
						"payload": {
							"message": {
								"text": this.historyTextList
							}
						}
					};
					console.log("请求的params：" + JSON.stringify(params))
					this.sparkResult = this.sparkResult + "\r\n我：" + this.TEXT + "\r\n"
					this.sparkResult = this.sparkResult + "萌芽助手："
					console.log("发送第一帧...", params)
					realThis.socketTask.send({ // 发送消息，，都用uni的官方版本
						data: JSON.stringify(params),
						success() {
							console.log('第一帧发送成功')
						}
					});
				});

				// 接受到消息时
				realThis.socketTask.onMessage((res) => {
					console.log('收到API返回的内容：', res.data);
					let obj = JSON.parse(res.data)
					// console.log("我打印的"+obj.payload);
					let dataArray = obj.payload.choices.text;
					for (let i = 0; i < dataArray.length; i++) {
						realThis.sparkResult = realThis.sparkResult + dataArray[i].content
						realThis.tempRes = realThis.tempRes + dataArray[i].content
					}
					// realThis.sparkResult =realThis.sparkResult+ 
					let temp = JSON.parse(res.data)
					// console.log("0726",temp.header.code)
					if (temp.header.code !== 0) {
						console.log(`${temp.header.code}:${temp.message}`);
						realThis.socketTask.close({
							success(res) {
								console.log('关闭成功', res)
								realThis.wsLiveFlag = false;
							},
							fail(err) {
								console.log('关闭失败', err)
							}
						})
					}
					if (temp.header.code === 0) {
						this.$nextTick(() => {
							// 获取scroll-view的ref并在适当的时候滚动到底部
							uni.createSelectorQuery().in(this).select('.main_block').scrollOffset(item => {
								console.log(item)
								this.scrollTop = item.scrollHeight - 5
							}).exec()
						})
						// this.$nextTick(() => {
						// 	let scrollElem = this.$refs.mainBlock;
						// 	// scrollElem.$el.scrollTo({ 
						// 	// 	top: scrollElem.$el.scrollHeight, 
						// 	// 	behavior: 'smooth' ,
						// 	// });
						// });
						if (res.data && temp.header.status === 2) {
							realThis.sparkResult = realThis.sparkResult +
								"\r\n**********************************************"
							this.historyTextList.push({
								"role": "assistant",
								"content": this.tempRes
							})
							this.currentStatus = 'end'
							this.TEXT = ''
							// 提交到服务器
							const newData = {
								idNo: idNo,
								chatResult: this.tempRes
							}
							// request.postJson(
							// 	'/userChatLogs/idNo,' + idNo, newData
							// ).then(res => {
							// }).catch(err => {
							// 	console.log(err)
							// 	uni.showModal({
							// 		title: '提示',
							// 		content: err.data.message,
							// 		showCancel: false
							// 	})
							// })
							
							/* let dataArray= obj.payload.choices.text;
							for(let i=0;i<dataArray.length;i++){
								realThis.sparkResult =realThis.sparkResult+ dataArray[i].content
							} */
							setTimeout(() => {
								realThis.socketTask.close({
									success(res) {
										console.log('关闭成功', res)
									},
									fail(err) {
										// console.log('关闭失败', err)
									}
								})
							}, 1000)
						}
					}
				})
			},
			// 鉴权
			getWebSocketUrl() {
				console.log(this.httpUrl)
				var httpUrlHost = (this.httpUrl).substring(8, 28);
				var httpUrlPath = (this.httpUrl).substring(28);
				console.log(httpUrlHost)
				console.log(httpUrlPath)
				switch (httpUrlPath) {
					case "/v1.1/chat":
						this.modelDomain = "general";
						break;
					case "/v2.1/chat":
						this.modelDomain = "generalv2";
						break;
					case "/v3.1/chat":
						this.modelDomain = "generalv3";
						break;
					case "/v3.5/chat":
						this.modelDomain = "generalv3.5";
						break;
				}
				console.log(this.modelDomain)


				return new Promise((resolve, reject) => {
					// https://spark-api.xf-yun.com/v1.1/chat  V1.5 domain general
					// https://spark-api.xf-yun.com/v2.1/chat  V2.0 domain generalv2
					var url = "wss://"+httpUrlHost+httpUrlPath;
					var host = "spark-api.xf-yun.com";
					var apiKeyName = "api_key";
					var date = new Date().toGMTString();
					var algorithm = "hmac-sha256";
					var headers = "host date request-line";
					var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrlPath} HTTP/1.1`;
					var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.APISecret);
					var signature = CryptoJS.enc.Base64.stringify(signatureSha);
					var authorizationOrigin =
						`${apiKeyName}="${this.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
					var authorization = CryptoJS.enc.Base64.stringify(authorizationOrigin);
					url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;

					// console.log(url)
					resolve(url); // 主要是返回地址
				});
			},
			
			
		},
		onShareAppMessage(res) {
			const userInfo = storageData.getLoginUser()
			console.log(userInfo)
			
			if (res.from === 'button') {
				// 来自页面内分享按钮
			}
			return {
				title: '小奕口算:智能助理上线了',
				path: '/pages/mathAssistant/mathAssistant?shareUc=' + userInfo.userCode,
				mpId: 'wxcbbe1a868c5c3c3c', //此处配置微信小程序的AppId
			}
		},
		onShareTimeline(res) {
			const userInfo = storageData.getLoginUser()
			return {
				title: '小奕口算:智能助理上线了',
				path: '/pages/mathAssistant/mathAssistant?shareUc=' + userInfo.userCode,
				mpId: 'wxcbbe1a868c5c3c3c', //此处配置微信小程序的AppId
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page_wrapper{
		.chat_title_block{
			font-size: 16px;
			font-weight: 400;
			margin: 15px 15px 0px;
		}
		.main_block{
			flex: 1;
			margin: 15px;
			padding: 15px;
			overflow-y: scroll;
			background-color: white;
			line-height: 30px;
			font-size: 16px;
			width: auto;
			display: flex;
			.user_name{
				color: orange;
				font-weight: 500;
			}
		}
		.user_content_block{
			margin: 0px 15px;
			display: flex;
			.user_content{
				flex: 1;
				padding: 15px 20px;
				background-color: white;
			}
		}
		.bottom_btns_block{
			.fcz_btn{
				width: 90%;
				height: 40px;
				color: white;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 5px;
			}
			.send_msg{
				background: linear-gradient(to right, #009688, #00b8d4); /* 渐变从蓝绿色到稍浅的蓝绿色 */  
			}
			.sending_msg{
				background: linear-gradient(to right, #FF4500, #FF8C00); /* 渐变从蓝绿色到稍浅的蓝绿色 */ 
			}
		}
	}
</style>